package com.tms.app.tms.db;


import com.tms.app.tms.app.MyApp;
import com.tms.app.tms.bean.Msg;
import com.tms.app.tms.utils.SharePreferenceUtil;

import org.xutils.DbManager;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.List;

import cn.edu.zafu.camera.HeadChar;

/**
 * Created by Administrator on 2017/12/8 0008.
 */

public class MsgDBUtil extends DBUtil {
    public static void saveOrUpadateMsg(Msg msg,int type){
        String mobile= SharePreferenceUtil.getString(MyApp.getInstance().getApplicationContext(),"mobile","");
        if (mobile==null||mobile.equals(""))
            return;
        try {
            DbManager db = x.getDb(MyApp.getDaoConfig());
            if (msg.getMsgId()>0){
                Msg localMsg=db.selector(Msg.class).where("msgId","=",msg.getMsgId())
                        .and("mobile","=",mobile)
                        .findFirst();
                if (localMsg!=null&&localMsg.getId()>0)
                {
                    msg.setId(localMsg.getId());
                }
                msg.setMobile(mobile);
                if(msg.getMsgType()!=2){
                    msg.setMsgType(type);
                }
                db.saveOrUpdate(msg);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }


    }

//type 0任务消息,1系统消息,2 变更通知
    public static void upadateMsgReadStatus(int msgId,int type,int readStatus){
        String mobile= SharePreferenceUtil.getString(MyApp.getInstance().getApplicationContext(),"mobile","");
        if (mobile==null||mobile.equals(""))
            return;
        try {
            DbManager db = x.getDb(MyApp.getDaoConfig());

            WhereBuilder whereBuilder=WhereBuilder.b("mobile","=",mobile)
                    .and("msgType","=",type);
            if (msgId>0){
                whereBuilder. and("msgId","=",msgId);
            }
           db.update(Msg.class,whereBuilder,new KeyValue("readStatus",readStatus));
        } catch (DbException e) {
            e.printStackTrace();
        }


    }

    public static void saveOrUpadateMsg(List<Msg> list,int type){
        for (Msg msg : list) {
            saveOrUpadateMsg(msg,type);
        }
    }

    public static  List<Msg>  getMsgListByType(int msgType){
        String mobile= SharePreferenceUtil.getString(MyApp.getInstance().getApplicationContext(),"mobile","");
        if (mobile==null||mobile.equals(""))
            return null;
        try {
            DbManager db = x.getDb(MyApp.getDaoConfig());
            List<Msg> listSort = db.selector(Msg.class).where("msgType","=",msgType)
                       .and("mobile","=",mobile)
                       .orderBy("publishTime",true)
                       .findAll();
            return listSort;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }
}
